package com.mall.seckill.mq;

import com.alibaba.fastjson.JSONObject;
import com.mall.common.response.CommonResponse;
import com.mall.constant.strings.ConstantStrings;
import com.mall.entity.TbSeckillItem;
import com.mall.entity.bargain.BgOrder;
import com.mall.seckill.mapper.SeckillItemMapper;
import com.mall.seckill.service.SeckillOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 消费
 *
 * @author ASUS
 * @date 2021/07/18
 */
@Component
public class Consume {

    @Autowired
    private SeckillItemMapper seckillItemMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillOrderService seckillOrderService;

    @JmsListener(destination = "order")
    public void listenOrder(String message){
        System.out.println("消费者接收到消息：" + message);
        JSONObject jsonObject = JSONObject.parseObject(message);
        Long uid = jsonObject.getLong("uid");
        Long itemId = jsonObject.getLong("itemId");
        TbSeckillItem item = seckillItemMapper.findOne(itemId);
        //添加订单信息
        BgOrder bgOrder = new BgOrder();
        bgOrder.setCreateTime(new Date());
        bgOrder.setPrice(item.getSeckillPrice());
        bgOrder.setType("秒杀");
        bgOrder.setItemSpecId(item.getItemSpecId());
        bgOrder.setUid(uid);
        bgOrder.setStatus("0");
        bgOrder.setOrderItemId(itemId);
        seckillOrderService.insert(bgOrder);
        String ifOrderId= ConstantStrings.IF_SECKILL_ORDER_ID+bgOrder.getId();
        redisTemplate.opsForValue().set(ifOrderId,"",10, TimeUnit.SECONDS);
    }

}
